/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pato
 */
public class actualizarThread extends Thread {

    String consulta, id,fecha="";
    int total = 0;

    public void run() {
        VentanaPrincipal.sincronizar(true);
        local_connection.reconnect(60000);
        VentanaPrincipal.baseDatos.setText("Actualizando Base de Datos");
        VentanaPrincipal.actualizacion.setValue(0);
        calcularTotal();
        volcarDatos();
        actualizarDatos();
        actualizarEspeciales();
        actualizarStock();
        VentanaPrincipal.baseDatos.setText("Base de datos Actualizada");
        local_connection.reconnect(5000);
        VentanaPrincipal.sincronizar(false);
    }

    private void calcularTotal() {
        try {
             PreparedStatement ps = (PreparedStatement) cache_connection.cn.prepareStatement("select  datetime(fecha, 'localtime') from actualizacion order by id desc limit 1");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                fecha = rs.getString(1);
            } else {
                fecha = "0000-00-00 00:00:00";
            }
             ps = (PreparedStatement) cache_connection.cn.prepareStatement("SELECT count(*) FROM cache where respaldado = 0");
             rs = ps.executeQuery();
            if (rs.next()) {
                total += rs.getInt(1);
            }
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("select count(*) from cambios where fecha >= ? ");
            ps.setString(1, fecha);
            rs = ps.executeQuery();
            if (rs.next()) {
                total += rs.getInt(1);
            }
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("select count(*) from stock where sucursal = ?");
            ps.setInt(1, VentanaPrincipal.sucursal);
            rs = ps.executeQuery();
            if (rs.next()) {
                total += rs.getInt(1);
            }
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("select count(*) from especiales");
            rs = ps.executeQuery();
            if (rs.next()) {
                total += rs.getInt(1);
            }
            VentanaPrincipal.actualizacion.setMaximum(total);
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }

    }

    private void volcarDatos() {

        try {
            cache_connection.cn.setAutoCommit(false);
            local_connection.cn.setAutoCommit(false);
            PreparedStatement ps = (PreparedStatement) cache_connection.cn.prepareStatement("SELECT consulta,tabla FROM cache where respaldado = 0 order by tabla desc");
            ResultSet rs = ps.executeQuery();
            int i = 0;
            while (rs.next()) {
                ps = local_connection.cn.prepareStatement(" " + rs.getString(1) + " ");
                //  System.out.println(rs.getString(1));
                ps.execute();
                VentanaPrincipal.actualizacion.setValue(VentanaPrincipal.actualizacion.getValue()+1);
            }
            ps = cache_connection.cn.prepareStatement("UPDATE cache SET respaldado = 1");
            ps.execute();
            local_connection.cn.commit();
            cache_connection.cn.commit();
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    private void actualizarDatos() {
        try {
            
            PreparedStatement ps = (PreparedStatement) local_connection.cn.prepareStatement("select id,consulta,tabla from cambios where fecha >= ? order by tabla");
            ps.setString(1, fecha);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                //tabla = rs.getString("tabla");
                id = rs.getString("id");
                consulta = rs.getString("consulta");
                // System.out.println(" "+consulta+" ");
                if (consulta != null) {
                    consulta = consulta.replace(" do ", " select ");
                    consulta = consulta.replace("LIMIT 1", "");
                    try {
                        ps = (PreparedStatement) cache_connection.cn.prepareStatement(" " + consulta + " ");
                        ps.execute();
                    } catch (SQLException ex) {
                        VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                        VentanaPrincipal.logger.log(Level.SEVERE, null, consulta);
                        System.out.println(consulta + "    " + id);
                    }
                }
                ps = (PreparedStatement) cache_connection.cn.prepareStatement("insert into actualizacion (idremoto) values(?)");
                ps.setString(1, id);
                ps.execute();
                VentanaPrincipal.actualizacion.setValue(VentanaPrincipal.actualizacion.getValue()+1);
            }
                local_connection.cn.commit();
                cache_connection.cn.commit();
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            VentanaPrincipal.logger.log(Level.SEVERE, null, consulta);
            System.out.println(consulta + "    " + id);
        }
    }

    void actualizarStock() {
        try {
            int i = 0;
            PreparedStatement ps = (PreparedStatement) local_connection.cn.prepareStatement("select cantidad,id_producto from stock where sucursal = ?");
            ps.setInt(1, VentanaPrincipal.sucursal);
            ResultSet rs = ps.executeQuery();
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("update stock set cantidad = ? where sucursal = ? and id_producto = ?");
            ps.setInt(2, VentanaPrincipal.sucursal);
            while (rs.next()) {
                ps.setInt(1, rs.getInt(1));
                ps.setInt(3, rs.getInt(2));
                ps.execute();
                VentanaPrincipal.actualizacion.setValue(VentanaPrincipal.actualizacion.getValue()+1);
            }

            local_connection.cn.commit();
            cache_connection.cn.commit();
            cache_connection.cn.setAutoCommit(true);
            local_connection.cn.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(ActualizarRegistros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void actualizarEspeciales() {
        try {
            PreparedStatement ps = local_connection.cn.prepareStatement("select * from especiales");
            ResultSet rs = ps.executeQuery();
            ps = cache_connection.cn.prepareStatement("delete from especiales");
            ps.execute();
            ps = cache_connection.cn.prepareStatement("insert into especiales values(null,?,?,?,?,?,?)");
            while (rs.next()) {
                ps.setInt(1, rs.getInt("id_producto"));
                ps.setString(2, rs.getString("clave"));
                ps.setInt(3, rs.getInt("sucursal"));
                ps.setString(4, rs.getString("tipo"));
                ps.setString(5, rs.getString("fecha"));
                ps.setInt(6, rs.getInt("vendido"));
                ps.execute();
                VentanaPrincipal.actualizacion.setValue(VentanaPrincipal.actualizacion.getValue()+1);
            }
            local_connection.cn.commit();
            cache_connection.cn.commit();
        } catch (SQLException ex) {
            Logger.getLogger(ActualizarRegistros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
